package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import cn.tedu._03vehicle.mapper.UserMapper;
import cn.tedu._03vehicle.pojo.dto.UserLoginParam;
import cn.tedu._03vehicle.pojo.dto.UserRegParam;
import cn.tedu._03vehicle.pojo.entity.User;
import cn.tedu._03vehicle.pojo.vo.UserLoginVo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.naming.ldap.PagedResultsControl;
import java.util.Date;
@Slf4j
@Tag(name="用户功能")
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @ApiOperationSupport(order = 10)
    @Operation(summary = "注册")
    public JsonResult reg(@RequestBody @Validated UserRegParam param)
    {
        String username=param.getUsername();
        int x=userMapper.isExist(username);
        if(x>0)
        {
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(param, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int y=userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @PostMapping("Login")
    @ApiOperationSupport(order = 20)
    @Operation(summary = "登录")
    public JsonResult Login(@RequestBody UserLoginParam param, HttpSession session)
    {
        log.debug("logging...");
        UserLoginVo res=userMapper.userLogin(param);
        if(res==null)
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        //

        session.setAttribute("user",res);
        return JsonResult.ok(res);
    }

    @GetMapping("currentUser")
    @ApiOperationSupport(order = 30)
    @Operation(summary = "获取当前用户")
    public JsonResult currentUser(HttpSession session)
    {
        UserLoginVo userLoginVo=(UserLoginVo)session.getAttribute("user");
        return JsonResult.ok();
    }

    @GetMapping("exit")
    @ApiOperationSupport(order = 40)
    @Operation(summary = "退出登录")
    public void exit(HttpSession session)
    {
        session.removeAttribute("user");
    }
}














